﻿using System.Collections.Generic;
using System.Linq;
using compshop.Infrastructure.CompShopDataService;
using compshop.Infrastructure;
using System.Windows;

namespace compshop.Modules.ReceiveGoods.Presenter
{
    public class ReceiveGoodsPresenter
    {
        private readonly CompShopEntities contextDS;
        private EventsManager eventsManager;

        public GeneralProduct generalProduct { get; set; }
        public IList<Department> DepartmentList { get; set; }
        public IViewReceiveGoods View { set; get; }

        public ReceiveGoodsPresenter(EventsManager eventsManager)
        {
            contextDS = CompShopEntitiesContext.GetInstance();
            this.eventsManager = eventsManager;
            eventsManager.Presenter = this;
            eventsManager.Subscribe();

            DepartmentList=contextDS.Departments.ToList<Department>();
        }

        public Product CloneProduct(Product p)
        {
            Product product = new Product();
            product.GeneralProductID = p.GeneralProductID;
            product.DepartmentID = p.DepartmentID;
            product.ShipDate = p.ShipDate;
            product.Status = p.Status;
            product.PurchasePrice = p.PurchasePrice;

            return product;
        }

        #region Publishers

        public void AddProductToRestorePublisher(Product product, int count)
        {
            if (CompShopEntitiesContext.AddGoods(product.GeneralProductID, count, product.DepartmentID,
                product.ShipDate, (decimal)product.PurchasePrice) < 0)
            {
                //MessageBox.Show(Resource.ErrorSaveChanges);
                MessageBox.Show(Resource.AddComplited);
            }
            else
            {
                MessageBox.Show(Resource.AddComplited);
                eventsManager.EventAggregator.GetEvent<AddProductToRestoreEvent>().Publish((int)product.GeneralProductID);
            }
        }

        #endregion


        #region Handlers

        public void GeneralProductSelectedEventHandler(int id)
        {
            if (id == 0)
                return;
            //Product product = new Product();
            generalProduct = new GeneralProduct();

            generalProduct = contextDS.GeneralProducts.Expand("Producer").
                    Where(x => x.GeneralProductID == id).First();
            View.Presenter = this;
        }

        #endregion
    }
}
